<?php
class ControllerCategoryProduct extends Controller {
    private $error = array();

    public function add()
    {
        $language_id = $this->config->get('config_language_id');
        $cooker_comment_attribute_id = $this->config->get('cooker_comment_attribute_id');
        $cook_time_option_id = $this->config->get('cook_time_option_id');
        $cook_time_option_value_id = $this->config->get('cook_time_option_value_id');
        

        if (!$this->actionCheck(true,true)) {
            return;
        }
        
        if(!$this->validate())
        {
            if (count($this->error)>0) {
                $error_warning = array_shift($this->error);
            } else {
                $error_warning = '';
            }
            $this->response->setDataResult(0,$error_warning,null);
            return;
        }
        
        $this->load->model('category/product');
        
        $product = array (
            'product_description' => array (),
            'image' => '',
            'model' => '',
            'sku' => '',
            'upc' => '',
            'ean' => '',
            'jan' => '',
            'isbn' => '',
            'mpn' => '',
            'location' => '',
            'price' => '0.0000',
            'tax_class_id' => '0',
            'quantity' => '1000',
            'minimum' => '1',
            'subtract' => '0',
            'stock_status_id' => '5',
            'shipping' => '1',
            'keyword' => '',
            'date_available' => '2009-02-03',
            'length' => '0.00000000',
            'width' => '0.00000000',
            'height' => '0.00000000',
            'length_class_id' => '1',
            'weight' => '1.00000000',
            'weight_class_id' => '1',
            'status' => '1',
            'sort_order' => '0',
            'manufacturer' => '',
            'manufacturer_id' => '0',
            'category' => '',
            'product_category' => array(),
            'filter' => '',
            'product_store' =>
            array (
                0 => '0',
            ),
            'download' => '',
            'related' => '',
            'product_attribute' => array(),
            'option' => '',
            'product_option' => array(),
            'product_image' => array(),
            'points' => '0',
            'product_reward' =>
            array (
                1 =>
                array (
                    'points' => '0',
                ),
            ),
            'product_layout' =>
            array (
                0 => '',
            ),
            'product_address_id' => '0',
            'address_type' => 1,
            'address' => '',
            'address_detail' => '',
            'lat' => '0',
            'lng' => '0',
            'mctx' => '0',
            'mcty' => '0',
            'items' => array()
        );
        
        if((int)$this->request->post['product_address_id']==0)
        {
            $this->log->write(json_encode($this->request->post));
            $this->load->model('tool/baidu');
        
            $product['address_type'] = 1;
            $product['address'] = $this->request->post['address'];
            
            if(isset($this->request->post['address_detail']))
            {
                $product['address_detail'] = $this->request->post['address_detail'];
            }
            
            $product['lat'] = $this->request->post['lat'];
            $product['lng'] = $this->request->post['lng'];
        
            $mct = $this->model_tool_baidu->BD09LLtoBD09MC($this->request->post['lng'],$this->request->post['lat']);
        
            if(!$mct)
            {
                $this->response->setDataResult(0,"坐标转换失败！",null);
                return;
            }
            else
            {
                if($mct->status !=0)
                {
                    $this->response->setDataResult(0,"坐标转换失败！".$mct->message,null);
                    return;
                }
                $point =  array_shift($mct->result);
                $product['mctx'] = $point->x;
                $product['mcty'] = $point->y;
            }
        }
        
        $product['product_description'][$language_id] = array (
                    'name' => $this->request->post['title'],
                    'description' => $this->request->post['description'],
                    'meta_title' => $this->request->post['title'],
                    'meta_description' => '',
                    'meta_keyword' => '',
                    'tag' => '',
                );
        foreach ($this->request->post['images'] as $image) {
            $product['image'] = $image;
            break;
        }
        foreach ($this->request->post['images'] as $image) {
            $product['product_image'][] = array(
                'image' => $image,
                'sort_order' => '0'
            );
        }
        
        $product['model'] = $this->request->post['title'];
        
        $product['price'] = $this->request->post['price'];
        
        $product['quantity'] = $this->request->post['quantity'];
        
        $product['product_address_id'] = $this->request->post['product_address_id'];
        
        $product['items'] = $this->request->post['items'];
        
        $product['product_category'][] = $this->request->post['category_id'];
        
        $product['product_attribute'][] =  array (
                    'name' => '厨师说',
                    'attribute_id' => $cooker_comment_attribute_id,
                    'product_attribute_description' =>
                    array (
                        $language_id =>
                        array (
                            'text' => $this->request->post['description'],
                        ),
                    ),
                );
        
        $time_option =  array (
                'product_option_id' => '',
                'name' => '就餐时间',
                'option_id' => $cook_time_option_id,
                'type' => 'radio',
                'required' => '1',
                'product_option_value' => array()
            );
        $max_time = new DateTime($product['date_available']);
        foreach ($this->request->post['times'] as $product_time) {
            $time_option['product_option_value'][] = array(
                'option_value_id'=>$cook_time_option_value_id,
                'quantity'=>$this->request->post['quantity'],
                'subtract' => '1',
                'price' => '0',
                'price_prefix' => '+',
                'points' => '0',
                'points_prefix' => '+',
                'weight' => '0',
                'weight_prefix' => '+',
                'time'=>$product_time['time']
            );
           
            $datetime = new DateTime($product_time['time']);
            
            if($datetime > $max_time)
            {
                $max_time = $datetime;
            }
        }
        
        $product['date_available'] = $max_time->format('Y-m-d H:i:s');

        
        
        if(isset($this->request->post['edit_product']))
        {
            if(!$this->editValidate())
            {
                if (count($this->error)>0) {
                    $error_warning = array_shift($this->error);
                } else {
                    $error_warning = '';
                }
                $this->response->setDataResult(0,$error_warning,null);
                return;
            }
            $product_id = $this->request->post['product_id'];
            $product_info = $this->model_category_product->getSimpleProductByProductId($product_id);
            if($product_info)
            {
                $offset_quantity = $product['quantity'] - $product_info['quantity'];
                $soptions = $this->model_category_product->getProductOptions($product_id);
                foreach ($soptions as $soption) {
                    if($soption['option_id'] == $cook_time_option_id)
                    {
                        foreach ($time_option['product_option_value'] as $k => $toption) {
                            foreach ($soption['product_option_value'] as $stoption) {
                                if($this->timeEqual($toption['time'],$stoption['time']))
                                {
                                    $time_option['product_option_value'][$k]['quantity'] = $stoption['quantity'] + $offset_quantity;
                                    $this->log->write('equal' . $time_option['product_option_value'][$k]);
                                    if($time_option['product_option_value'][$k]<0)
                                    {
                                        $time_option['product_option_value'][$k] = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $product['product_option'][] = $time_option;
            $this->model_category_product->editProduct($product_id,$product);
        }
        else 
        {
            $product['product_option'][] = $time_option;
            $product_id = $this->model_category_product->addProduct($product);
        }
        
        $this->response->setDataResult(1,"",$product_id);
    }
    
    public function edit()
    {
        $this->request->post['edit_product'] = true;
        $this->add();
    }
    
    public function delete()
    {
        if (!$this->actionCheck(true,false)) {
            return;
        }
        $this->load->model('category/product');

        if(!$this->editValidate())
        {
            if (count($this->error)>0) {
                $error_warning = array_shift($this->error);
            } else {
                $error_warning = '';
            }
            $this->response->setDataResult(0,$error_warning,null);
            return;
        }
        else
        {
            $this->load->model('catalog/product');
            $this->model_catalog_product->deleteProduct($this->request->post['product_id']);
            $this->response->setDataResult(1,"",null);
            return;
        }
         
    }
    
    // by zhengrunqiang
    public function addchatgroup(){
       $product_id = $this->request->post['product_id'];
       $group_id = $this->request->post['chat_group_id'];
       $this->load->model('category/product');
       $this->model_category_product->AddProductChatgroupId($product_id,$group_id);
    }
    
    protected function editValidate()
    {
        if(!isset($this->request->post['product_id']))
        {
            $this->error['product_id'] = '缺少参数 product_id ！';
            return !$this->error;
        }
        
        if(!$this->model_category_product->getTotalProductsByProductIdAndCustomer($this->request->post['product_id']))
        {
            $this->error['product_id'] = '无权修改该product ！';
        }
        return !$this->error;
    }
    
    protected function validate()
    {
        if (!isset($this->request->post['title']) || (utf8_strlen($this->request->post['title']) < 1) || (utf8_strlen($this->request->post['title']) > 64)) {
            $this->error['title'] = '请填写美食标题！';
        }
        
        if (!isset($this->request->post['description']) || (utf8_strlen($this->request->post['description']) < 1) || (utf8_strlen($this->request->post['description']) >500)) {
            $this->error['description'] = '请填写美食描述！';
        }
        if(!isset($this->request->post['items']))
        {
            $this->error['items'] = '请填写菜品！';
        }
        else
        {
            foreach ($this->request->post['items'] as $item) {
                if ((utf8_strlen($item['name']) < 1) || (utf8_strlen($item['name']) > 255)) {
                    $this->error['name'] = '请输入菜品标题！';
                }
            }
        }

        
        if(!isset($this->request->post['price']))
        {
            $this->error['price'] = '请输入美食价格！';
        }
        
        if(!isset($this->request->post['quantity']))
        {
            $this->error['quantity'] = '请输入限购人数！';
        }
        
        if(!isset($this->request->post['times']))
        {
            $this->error['times'] = '请填写用餐时间！';
        }
        else
       {
            foreach ($this->request->post['times'] as $time) {
                if ((utf8_strlen($time['time']) < 1) || (utf8_strlen($time['time']) > 255)) {
                    $this->error['time'] = '请选择用餐时间！';
                }
            }
        }
        if(!isset($this->request->post['images']))
        {
            $this->error['images'] = '请添加菜品图片！';
        }
        if(!isset($this->request->post['product_address_id']))
        {
            $this->error['product_address_id'] = '请填写用餐地址！';
        }
        
        
        return !$this->error;
    }
    
    protected function timeEqual($time1,$time2)
    {
        $t1 = new DateTime($time1);
        $t2 = new DateTime($time2);
        if($t1 && $t2 && $t1->format('Y-m-d H:i') == $t2->format('Y-m-d H:i'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    
    
}